
import ts = require('typescript');
import JsLoader from './JsLoader';
import Loader from './Loader';
import File from '../file/File';

const DEFAULT_COMPILER_OPTIONS: ts.CompilerOptions = {
    strict: false,
    strictAll: false,
    strictFunctionTypes: false,
    strictPropertyInitialization: false,
    strictNullChecks: false,
    module: ts.ModuleKind.ESNext,
    target: ts.ScriptTarget.Latest,
    jsx: ts.JsxEmit.Preserve
};

export default class TsLoader extends JsLoader {

    defaultLoader = new Loader();

    async load(file: File) {
        if ((file.src as string).toLowerCase().endsWith('.d.ts')) {
            return file.cx.defaultLoader.load(file);
        }
        let content = await file.contents;
        let options = {
            reportDiagnostics: true,
            fileName: file.src,
            compilerOptions: Object.assign({}, DEFAULT_COMPILER_OPTIONS, file.cx.options.typescript)
        };
        let result = ts.transpileModule(content, options);
        if (result.diagnostics && result.diagnostics.length) {
            throw new Error('TsLoader Error:\n' + result.diagnostics.map(
                (e: any) => e.file.path + ':' + e.start + ':' + e.length + ': ' + e.messageText).join('\n')
            );
        }
        file.contents = result.outputText;
        await super.load(file);
    }
}
